package cn.edu.zafu.bigdata.x.zhouyuyan.work10;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.channels.DatagramChannel;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class UDPServer {
    private static final int port = 12345;
    private static final String time_format = "yyyy-MM-dd HH:mm:ss";

    public static void main(String[] args) {
        try (DatagramSocket socket = new DatagramSocket(port)){
            byte[] buffer = new byte[1024];
            while (true){
                DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
                socket.receive(packet);

                String request = new String(packet.getData(),0,packet.getLength());
                System.out.println("收到请求：" + request);

                LocalDateTime now = LocalDateTime.now();
                String timeString = now.format(DateTimeFormatter.ofPattern(time_format));

                InetAddress clientAddress = packet.getAddress();
                int clientProt = packet.getPort();
                byte[] responseData = timeString.getBytes();
                DatagramPacket responsePacket = new DatagramPacket(responseData, responseData.length,clientAddress,clientProt);
                socket.send(responsePacket);

                System.out.println("已发送时间响应：" + timeString + " 到 " + clientAddress.getHostAddress());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
